<template>
  <!-- <a-card title="菜单分配" :bordered="true" type="inner"> -->
    <div ref="appModal">
    <a-modal
    class="modalWrap"
     @ok="addAction"
      @cancel="onClose"
      :title="title + '角色'"
      :width="420"
      :visible="drawerVisible"
      :wrapStyle="{overflow: 'auto',paddingBottom: '108px'}"
      :getContainer="()=>$refs.appModal"
    >
      <!-- :wrapStyle="{height: 'calc(100% - 108px)',overflow: 'auto',paddingBottom: '108px'}" -->
    <!-- <a href="#" slot="extra">保存</a> -->
    <!-- <a-button type="primary" :disabled="!id" slot="extra" @click="save">保存</a-button> -->
    <a-form :form="form">
      <!-- <a-form-item label="角色编号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-input
          placeholder="请输入角色编号"
          @change="nameChange"
          v-decorator="['num', { rules: [{required:true, message: '请输入角色编号'}] }]"
        ></a-input>
      </a-form-item> -->
      <a-form-item label="名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-input
          placeholder="请输入角色名称"
          @change="nameChange"
          v-decorator="['name', { rules: [{required:true, message: '请输入角色名称'}] }]"
        ></a-input>
      </a-form-item>
      <!-- <a-form-item label="角色类型" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-radio-group v-model="submitData.roleType" buttonStyle="solid">
          <a-radio-button v-for="(item, index) in rolesList" :key="index" :value="item.value">{{ item.label }}</a-radio-button>
        </a-radio-group>
      </a-form-item> -->
      <a-form-item label="备注" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-input
          placeholder="请输入备注"
          @change="descriptionChange"
          v-decorator="['description', { rules: [{required:true, message: '请输入备注'}] }]"
        ></a-input>
      </a-form-item>
      <div class="splitLine"></div>
      <a-form-item label="名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-tree
          checkable
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          v-model="checkedKeys"
          @select="onSelect"
          @check="check"
          :selectedKeys="selectedKeys"
          :treeData="treeData"
        />
      </a-form-item>
    </a-form>
    <!-- <div :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }"> -->
        <!-- <a-button :style="{marginRight: '8px'}" :loading="confirmLoading || loading" @click="onClose">
          取消
        </a-button>
        <a-button @click="addAction" :loading="confirmLoading || loading" type="primary">确认</a-button> -->
      <!-- </div> -->
    </a-modal>
  <!-- </a-card> -->
  </div>
</template>

<script>
import * as API from "../../../api/role";
import { preventMoreClick } from '../../../utils/filter'

export default {
  data() {
    return {
      form: this.$form.createForm(this),
      treeData: [
      ],
      checkList: [],
      loading: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      // rolesList: [
      //   {value: 'MERCHANT', label: '商户'},
      //   {value: 'MANAGER', label: '管理员'}
      // ],
      submitData: {
        name: '',
        // description: '',
        menuTree: [],
        description: ''
        // num: null,
        // roleType: 'MERCHANT'
      },
    };
  },
  props: {
    id: {
      type: Number,
      detail: null
    },
    drawerVisible: {
      type: Boolean,
      detail: false
    },
    title: {
      type: String,
      detail: ""
    },
    confirmLoading: {
      type: Boolean,
      detail: false
    }
  },
  mounted () {
  },
  methods: {
    //  handleOk(e) {
    //   this.ModalText = 'The modal will be closed after two seconds';
    //   this.confirmLoading = true;
    //   setTimeout(() => {
    //     this.drawerVisible = false;
    //     this.confirmLoading = false;
    //     this.$emit('')
    //   }, 2000);
    // },
    handleCancel(e) {
      // console.log('Clicked cancel button');
      this.drawerVisible = false;
    },
    // getRolesmenuTreeList(id) {
    //   this.treeData = []
    //   this.checkedKeys = []
    //   // this.num = 0
    //   // 获取角色下菜单信息
    //   API.getRolesmenuTree(id).then(res => {
    //     if (res.code === 200) {
    //       this.treeData = res.data
    //       this.toMenu(res.data)
    //     }
    //   });
    // },
    getMenusList () { // 菜单初始值
      API.getMenus().then(res => {
        if (res.code === 200) {
          // console.log(res.data.records, 'res.data.records')
          this.treeData = res.data
        }
      });
    },
    // idCreate () {
    //   API.idCreate({str: 'JS-'}).then(res => {
    //     this.submitData.num = res.data
    //     this.setFields(this.submitData)
    //   })
    // },
    getRoleDetailList (id) {
        this.treeData = []
        this.checkedKeys = []

        this.submitData.name = ''
        this.submitData.description =''
        // this.submitData.description = ''
        // this.submitData.roleType = 'MERCHANT'
        this.submitData.menuTree = []
      if (id) {
        this.loading = true
        API.getRoleDetail(id).then(res => {
        if (res.code === 200) {
          this.submitData.name = res.data.name;
          // this.submitData.description = res.data.description;
          // this.submitData.num = res.data.num;
          // this.submitData.roleType = res.data.roleType || ''
          this.submitData.description = res.data.description || ''
          
          // this.submitData.menuTree = res.data.menuTree
          this.treeData = res.data.menuTree.sort((a, b) => {return a.menuSort - b.menuSort})
          this.toMenu(res.data.menuTree)
          this.setFields(this.submitData)
        }
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
      } else {
        this.setFields(this.submitData)
        this.getMenusList()
        // this.idCreate()
      }
      // console.log(this.submitData.menuTree)
    },
    setFields (submitData) { // form 回写
      this.form.setFieldsValue({
        name: submitData.name || undefined,
        description: submitData.description || undefined,
        // num: submitData.num || undefined
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys) {
      // console.log(selectedKeys, 111111)
      this.selectedKeys = selectedKeys;
    },
    check (val, e) {
      this.submitData.menuTree = []
      let arr = [...val, ...e.halfCheckedKeys]
      // let arr = [...val]
      console.log(222222222, val, e.halfCheckedKeys ,arr)
      this.toCount(this.treeData, arr)
      this.checkedKeys = val
      // console.log(this.submitData.menuTree)
      // this.submitData.menuTree = []
      // this.checkedKeys = val
      // this.checkList = checkedKeys
      // this.showParent(this.checkedKeys)
    },
    showParent (checkedKeys) {
      // let checkList = checkedKeys
      this.treeData.forEach((item) => {
        if (item.children) {
          item.children.forEach((_item) => {
            checkedKeys.includes(_item.key) && !checkedKeys.includes(item.key) && this.checkList.push(item.key)
          })
        }
      })
      this.toCount(this.treeData, this.checkList)
      // return checkList
    },
    onClose () {
      this.$emit("onClose");
    },
    nameChange(e) {
      this.submitData.name = e.target.value;
    },
    descriptionChange(e) {
      this.submitData.description = e.target.value;
    },
    // roleChange(value) {
    //   this.submitData.roleType = value;
    // },
    toMenu (treeData) {
      treeData.sort((a, b) => { return a.sort - b.sort })
      if (treeData.length) {
        treeData.forEach(item => {
          if (item.isDisplay) {
            if(item.children.length<=0) { 
              this.checkedKeys.push(item.nodeId) 
            }
            this.submitData.menuTree.push({nodeId: Number(item.nodeId), name:item.title})
            // this.submitData.menuTree.push(Number(item.nodeId))
            // this.checkedKeys.push(item.nodeId)
            // console.log(this.submitData.menuTree, 'this.submitData.menuTree')
          }
          if (item.children && item.children.length > 0) {
            this.toMenu(item.children)
          }
        });
      }
    },
    toCount (treeData, checkedKeys) {
      if (treeData.length) {
        treeData.forEach(item => {
          if (checkedKeys.includes(item.nodeId)) {
            this.submitData.menuTree.push({nodeId: Number(item.nodeId), name:item.title})
            // this.submitData.menuTree.push(Number(item.nodeId))
            // this.checkedKeys.push(item.nodeId)
          }
          if (item.children && item.children.length > 0) {
            this.toCount(item.children, checkedKeys)
          }
        });
      }
      // console.log(treeData, checkedKeys, 'treeData, checkedKeys', this.submitData.menuTree)
    },
    // save () {
    //   this.form.validateFields((err) => {
    //     if (!err) {
    //       preventMoreClick(this, () => { // 防重复点击
    //         this.$emit("save", this.submitData.menuTree);
    //       })
    //     }
    //   });
    // },
    addAction() {
      this.form.validateFields((err) => {
        if (!err) {
          preventMoreClick(this, () => { // 防重复点击
            this.$emit("addAction", this.submitData);
          })
        }
      });
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  },
  watch: {
    id: function(newVal) {
      if (newVal !== undefined) {
        this.getRoleDetailList(newVal)
      }
    }
  }
};
</script>
